package com.baoteng.network.manager;

import com.baoteng.network.executor.HttpExecutor;
import com.baoteng.network.model.NetworkConstants;

import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * <pre>
 *     desc   : 警告警告：其他module和App不要调用这个类
 *     desc   : 警告警告：其他module和App不要调用这个类
 *     desc   : 警告警告：其他module和App不要调用这个类
 *     desc   : 警告警告：其他module和App不要调用这个类
 *     version: 1.0
 * </pre>
 */
public class TokenManager {
    private URL tokenURL;
    private String currentToken;

    private TokenManager() {
    }

    public static TokenManager getInstance() {
        return Holder.INSTANCE;
    }

    public String getCurrentToken() {
        return currentToken == null ? "" : currentToken;
    }

    /**
     * 注意！！！对于服务端未维护token自动过期的，不提供主动获取token接口的，
     * 可在此单例内保存这次进程的token
     *
     * @param token
     */
    public void setCurrentToken(String token) {
        this.currentToken = token;
    }

    public String getTokenSync() {
        try {
            final String TOKEN_URL = NetworkConstants.TOKEN_URL;
            OkHttpClient client = HttpExecutor.getDefault().getHttpClient();
            Request req = new Request.Builder()
                    .url(TOKEN_URL)
                    .get()
                    .build();
            Response response = client.newCall(req).execute();
            ResponseBody body = response.body();
            String result = body.string();
            JSONObject jsonObject = new JSONObject(result);
            currentToken = jsonObject.getString("token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currentToken;
    }

    public boolean withoutToken(URL url) {
        if (url == null) {
            return false;
        }
        String urlStr = url.toString();
        for (String str : NetworkConstants.WITHOUT_TOKEN_URLS) {
            if (urlStr.contains(str)) {
                return true;
            }
        }
        return false;
    }

    private static class Holder {
        private static final TokenManager INSTANCE = new TokenManager();
    }
}
